package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.PoEventOpinionRelation;
import com.ruoyi.system.domain.PoPublicOpinion;
import com.ruoyi.system.domain.PublicOpinionEvents;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.enums.SensitiveTypeEnum;
import com.ruoyi.system.service.IGatherTaskService;
import com.ruoyi.system.service.IPoPublicOpinionService;
import com.ruoyi.system.service.IPublicOpinionEventsService;
import com.ruoyi.system.service.impl.EsUtil;
import com.ruoyi.system.task.TimeConsumingTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件Controller
 *
 * @author ruoyi
 * @date 2021-06-08
 */
@RestController
@RequestMapping("/system/events")
@Api(tags = "舆情：事件管理")
public class PublicOpinionEventsController extends BaseController {
    @Autowired
    private IPublicOpinionEventsService publicOpinionEventsService;
    @Autowired
    private IPoPublicOpinionService publicOpinionService;
    @Autowired
    private EsUtil esUtil;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IGatherTaskService gatherTaskService;


    /**
     * 获取事件概要
     */
    @ApiOperation("获取事件概要")
    @GetMapping("/getEventSummary/{eventId}")
    public AjaxResult getEventSummary(@PathVariable("eventId") Long eventId) {
        return AjaxResult.success(publicOpinionEventsService.getEventSummary(eventId));
    }


    /**
     * 负面信息热力图
     */
    @ApiOperation("负面信息热力图")
    @GetMapping("/negativeInformationHeatMap")
    public AjaxResult negativeInformationHeatMap(
            @RequestParam(value = "dayNum", required = false) int dayNum,
            @RequestParam(value = "eventId") long eventId) {

        Map<String, Object> map = new HashMap();
        //查询事件
        PublicOpinionEvents event = publicOpinionEventsService.selectPublicOpinionEventsById(eventId);
        //开始事件选取结束日期前dayNum
        Date currentDate= DateUtils.getCurrentDate();
        Date endTime;
        if(currentDate.getTime()<event.getEndTime().getTime()){
            endTime=currentDate;
        }else{
            endTime=event.getEndTime();
        }
        String[] dateList = DateUtils.getDateRange(endTime,dayNum);
        EventParameterVo parameter = new EventParameterVo();
        parameter.setEndDateTime(event.getEndTime());
        //开始事件选取结束日期前dayNum
        parameter.setStartDateTime(event.getStartTime());
        List<NameListValue> list = publicOpinionEventsService.groupSensitiveOpinionDayHour(SensitiveTypeEnum.Negative.name, event, parameter, null);
        map.put("dateList", dateList);
        map.put("heatData", list);
        return AjaxResult.success(map);
    }


    /**
     * 查询事件列表（非ES）
     */
    @ApiOperation("查询事件列表（非ES）")
    @PreAuthorize("@ss.hasPermi('event:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(PublicOpinionEvents publicOpinionEvents) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        publicOpinionEvents.setDeptId(user.getDeptId());
        publicOpinionEvents.setTenantCode(user.getTenantCode());
        startPage();
        List<PublicOpinionEvents> list = publicOpinionEventsService.selectPublicOpinionEventsList(publicOpinionEvents);
        return getDataTable(list);
    }


    /**
     * 导出事件列表
     */
    @ApiOperation("导出事件列表")
    @PreAuthorize("@ss.hasPermi('event:export')")
    @Log(title = "事件", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PublicOpinionEvents publicOpinionEvents) {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        publicOpinionEvents.setDeptId(user.getDeptId());
        publicOpinionEvents.setTenantCode(user.getTenantCode());
        List<PublicOpinionEvents> list = publicOpinionEventsService.selectPublicOpinionEventsList(publicOpinionEvents);
        ExcelUtil<PublicOpinionEvents> util = new ExcelUtil<PublicOpinionEvents>(PublicOpinionEvents.class);
        return util.exportExcel(list, "事件数据");
    }

    /**
     * 获取事件详细信息
     */
    @ApiOperation("获取事件详细信息")
    @PreAuthorize("@ss.hasPermi('event:query')")
    @GetMapping(value = "/{eventId}")
    public AjaxResult getInfo(@PathVariable("eventId") Long eventId) {
        return AjaxResult.success(publicOpinionEventsService.selectPublicOpinionEventsById(eventId));
    }



    /**
     * 新增事件
     */
    @ApiOperation("新增事件")
    @PreAuthorize("@ss.hasPermi('event:add')")
    @Log(title = "事件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PublicOpinionEvents event) {
        event.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        event.setDeptId(SecurityUtils.getLoginUser().getUser().getDeptId());
        event.setTenantCode(SecurityUtils.getLoginUser().getUser().getTenantCode());
        publicOpinionEventsService.insertPublicOpinionEvents(event);
        //创建采集任务
        gatherTaskService.batchCreateGatherTask(event);
        // 创建一个耗时任务对象
        TimeConsumingTask task = new TimeConsumingTask(event.getEventId(), null);
        // 创建一个线程对象，并将耗时任务对象作为参数传入
        Thread thread = new Thread(task);
        // 开启线程
        thread.start();
        return toAjax(true);
    }


    /**
     * 修改事件
     */
    @ApiOperation("修改事件")
    @PreAuthorize("@ss.hasPermi('event:edit')")
    @Log(title = "事件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PublicOpinionEvents publicOpinionEvents) {
        //先修改后更新es索引以确保es与数据库同步
        AjaxResult ajaxResult = toAjax(publicOpinionEventsService.updatePublicOpinionEvents(publicOpinionEvents));
        //重新创建采集任务
        gatherTaskService.batchUpdateGatherTask(publicOpinionEventsService.selectPublicOpinionEventsById(publicOpinionEvents.getEventId()));
        // 创建一个耗时任务对象
        TimeConsumingTask task = new TimeConsumingTask(publicOpinionEvents.getEventId(), null);

        // 创建一个线程对象，并将耗时任务对象作为参数传入
        Thread thread = new Thread(task);

        // 开启线程
        thread.start();
        return ajaxResult;
    }

    /**
     * 删除事件
     */
    @ApiOperation("删除事件")
    @PreAuthorize("@ss.hasPermi('event:remove')")
    @Log(title = "事件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{eventIds}")
    public AjaxResult remove(@PathVariable Long[] eventIds) {

        int res = publicOpinionEventsService.deletePublicOpinionEventsByIds(eventIds);
        //删除采集任务
        gatherTaskService.batchDeleteGatherTask("event", eventIds);
        return toAjax(res);
    }



    @ApiOperation("获取事件类型统计")
    @GetMapping("/getEventTypeCount")
    public AjaxResult getEventTypeCount() {
        List<NameValue> res = publicOpinionEventsService.getEventTypeCount();
        return AjaxResult.success(res);
    }


    /**
     * 根据事件id和舆情id
     * 修改舆情与事件的关系
     */
    @Log(title = "事件舆情关系", businessType = BusinessType.UPDATE)
    @PutMapping("/setRelation")
    public AjaxResult setRelation(@RequestBody PoEventOpinionRelation poEventOpinionRelation) {
        return AjaxResult.success(publicOpinionEventsService.setOpinionEventRelation(poEventOpinionRelation));
    }


    /**
     * 批量
     * 根据事件id和舆情id
     * 修改舆情与事件的关系
     */
    @Log(title = "事件舆情关系", businessType = BusinessType.UPDATE)
    @GetMapping("/setRelationBatch/{ids}")
    public AjaxResult setRelationBatch(@PathVariable String[] ids,
                                       @RequestParam(value = "type") String type,
                                       @RequestParam(value = "eventId") Long eventId) {
        return AjaxResult.success(publicOpinionEventsService.setRelationBatchEventRelation(ids, type, eventId));
    }


    /**
     * 获取正负面信息趋势图
     */
    @ApiOperation(value = "获取正负面信息趋势图", notes = "获取正负面信息趋势图")
    @GetMapping("/getSentimentByPublishTimeByEventId")
    public TableDataInfo getSentimentByPublishTimeByEventId(Long eventId) {
        List<NameListValue> list = publicOpinionEventsService.getSentimentByPublishTimeByEventId(eventId);
        return getDataTable(list);
    }

    /**
     * 信息载体趋势图
     */
    @ApiOperation(value = "信息载体趋势图", notes = "信息载体趋势图")
    @GetMapping("/getMediaTypeByPublishTimeByEventId")
    public TableDataInfo getMediaTypeByPublishTimeByEventId(Long eventId) {
        List<NameListValue> list = publicOpinionEventsService.getMediaTypeByPublishTimeByEventId(eventId);
        return getDataTable(list);
    }

    /**
     * 首发媒体溯源
     */
    @ApiOperation(value = "首发媒体溯源", notes = "首发媒体溯源")
    @GetMapping("/getFirstMediaReleasedByEventId")
    public TableDataInfo getFirstMediaReleasedByEventId(Long eventId) {
        List<PoPublicOpinion> list = publicOpinionEventsService.getFirstMediaReleasedByEventId(eventId);
        return getDataTable(list);
    }

    /**
     * 情感载体分析
     */
    @ApiOperation(value = "情感载体分析", notes = "情感载体分析")
    @GetMapping("/getMediaTypeSensitiveDayNumEvent")
    public TableDataInfo getMediaTypeSensitiveDayNumEvent(Long eventId) {
        List<NameListValue> list = publicOpinionEventsService.getMediaTypeSensitiveDayNumEvent(eventId);
        return getDataTable(list);
    }

    /**
     * 媒体活跃排行榜（情感）
     */
    @ApiOperation(value = "媒体活跃排行榜（情感）", notes = "媒体活跃排行榜（情感）")
    @GetMapping("/countSensitiveOpinionByMediaName")
    public TableDataInfo countSensitiveOpinionByMediaName(Long eventId) {
        List<OpMediaNameSensitiveDayNumVM> list = publicOpinionEventsService.countSensitiveOpinionByMediaName(eventId);
        return getDataTable(list);
    }


    /**
     * 意见领袖排行（情感）
     */
    @ApiOperation(value = "意见领袖排行（情感）", notes = "意见领袖排行（情感）")
    @GetMapping("/countSensitiveAuthorOpinion")
    public TableDataInfo countSensitiveAuthorOpinion(Long eventId) {
        List<OpAuthorSensitiveDayNumVM> list = publicOpinionEventsService.countSensitiveAuthorOpinion(eventId);
        return getDataTable(list);
    }


    /**
     * 获取事件热词
     */
    @ApiOperation(value = "获取事件热词", notes = "获取事件热词")
    @GetMapping("/getKeywordsByEventId")
    public TableDataInfo getKeywordsByEventId(Long eventId) {
        List<NameValue> list = publicOpinionEventsService.getKeywordsByEventId(eventId, 300);
        return getDataTable(list);
    }


    /**
     * 观点分析
     */
    @ApiOperation("观点分析")
    @GetMapping("/getViewpointAnalysis")
    public AjaxResult getViewpointAnalysis(Long eventId) {
        List<PoPublicOpinion> allMediaTypes = publicOpinionEventsService.getViewpointAnalysis(eventId);
        return AjaxResult.success(allMediaTypes);
    }


    /**
     * 舆情数量按省分组
     */
    @ApiOperation("舆情数量按省分组")
    @GetMapping("/getPublicOpinionCountGroupByProvinceOfEventId")
    public AjaxResult getPublicOpinionCountGroupByProvinceOfEventId(Long eventId) {
        List<NameValue> list = publicOpinionEventsService.getPublicOpinionCountGroupByProvinceOfEventId(eventId);
        return AjaxResult.success(list);
    }


    /**
     * 事件演化趋势分析(信息趋势图)
     */
    @ApiOperation("事件演化趋势分析(信息趋势图)")
    @GetMapping("/getPublicOpinionCountGroupByDayOfEventId")
    public AjaxResult getPublicOpinionCountGroupByDayOfEventId(Long eventId) {
        List<NameValue> list = publicOpinionEventsService.getPublicOpinionCountGroupByDayOfEventId(eventId);
        return AjaxResult.success(list);
    }


    /**
     * 事件关联人物
     */
    @ApiOperation(value = "事件关联人物", notes = "事件关联人物")
    @GetMapping("/getPersonsByEventId")
    public TableDataInfo getPersonsByEventId(Long eventId) {
        List<NameValue> list = publicOpinionEventsService.getPersonsByEventId(eventId, 300);
        return getDataTable(list);
    }

    /**
     * 事件关联区域
     */
    @ApiOperation(value = "事件关联区域", notes = "事件关联区域")
    @GetMapping("/getLocationsByEventId")
    public TableDataInfo getLocationsByEventId(Long eventId) {
        List<NameValue> list = publicOpinionEventsService.getLocationsByEventId(eventId, 300);
        return getDataTable(list);
    }

    /**
     * 事件关联机构
     */
    @ApiOperation(value = "事件关联机构", notes = "事件关联机构")
    @GetMapping("/getOrganizationsByEventId")
    public TableDataInfo getOrganizationsByEventId(Long eventId) {
        List<NameValue> list = publicOpinionEventsService.getOrganizationsByEventId(eventId, 300);
        return getDataTable(list);
    }

    /**
     * 主要舆情
     */
    @ApiOperation("主要舆情")
    @GetMapping(value = "/getMainPublicOpinion/{eventId}")
    public AjaxResult getMainPublicOpinion(@PathVariable("eventId") Long eventId) {
        return AjaxResult.success(publicOpinionEventsService.getMainPublicOpinion(eventId, 20));
    }

    /**
     * 舆情导读
     */
    @ApiOperation("舆情导读")
    @GetMapping(value = "/getGuideToReadingPublicOpinion/{eventId}")
    public AjaxResult getGuideToReadingPublicOpinion(@PathVariable("eventId") Long eventId) {
        return AjaxResult.success(publicOpinionEventsService.getGuideToReadingPublicOpinion(eventId, 20));
    }

    /**
     * 信息总览
     */
    @ApiOperation("信息总览")
    @GetMapping(value = "/getAllInformation")
    public AjaxResult getAllInformation(Long eventId) {
        return AjaxResult.success(publicOpinionEventsService.getAllInformation(eventId));
    }


}
